let App = getApp();
var i;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    disabled: false,
    nav_select: false, // 快捷导航
    region: '',
    detail: {},
    tempFilePaths: [],
    showImages:[],
    images: [],
    check_sex:0,
    age_group: [
      { name: '20以下', value: 0, checked: true },
      { name: '21岁~25岁', value: 1, checked: false },
      { name: '26岁~30岁', value: 2, checked: false },
      { name: '31岁~35岁', value: 3, checked: false },
      { name: '35岁以上', value: 4, checked: false },
    ],
    sex_index:0,//年龄段的下标
    is_age_group:0,//是否选择年龄段 1=是，0=否
    type_res: [
      { name: '待撩', value: 1, checked: true },
      { name: '单身', value: 2, checked: false },
      { name: '有主', value: 3, checked: false},
    ],
    dist_id:0,
    type:1,
    error: '',
  },

  onShow: function () {
    i = 0;
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //console.log(options);
    this.setData({
      dist_id: options.dist_id
    })
    if(options.address_id){
      // 获取当前地址信息
      this.getAddressDetail(options.address_id);
    }else{
      wx.navigateTo({
        url: '../address/create'
      })
    }
  },

  /**
   * 获取当前地址信息
   */
  getAddressDetail: function(address_id) {
    let _this = this;
    App._get('address/detail', {
      address_id
    }, function(result) {
      console.log(result);
      let showImagesArr = [];
      //展示图片
      if (result.data.detail.images) {
        for (var j = 0; j < result.data.detail.images.length; j++) {
          showImagesArr.push(App.root +  result.data.detail.images[j]);
        }
      }

      let type_res = _this.data.type_res;
      for (var j = 0; j < type_res.length; j++) {
        if (type_res[j].value == result.data.detail.type){
          type_res[j].checked = true;
        }else{
          type_res[j].checked = false;
        }
      }
      _this.setData(result.data);
      _this.setData({
        check_sex: result.data.detail.sex,
        type: result.data.detail.type,
        type_res: type_res,
        images: result.data.detail.images,
        showImages: showImagesArr,
        is_age_group: result.data.detail.is_age_group,
        sex_index: result.data.detail.age_group,
      })
    });
  },

  /**
   * 表单提交
   */
  saveData: function(e) {
    let _this = this,
      values = e.detail.value
    values.region = this.data.region;
    values.sex = this.data.check_sex;
    values.images = this.data.images;
    values.type = this.data.type;
    values.dist_id = this.data.dist_id;
    values.is_age_group = this.data.is_age_group;//是否选择
    if (this.data.is_age_group == 1){
      values.age_group = this.data.age_group[this.data.sex_index].value;
    }
    // 记录formId
    //App.saveFormId(e.detail.formId);

    // 表单验证
    if (!_this.validation(values)) {
      App.showError(_this.data.error);
      return false;
    }

    // 按钮禁用
    _this.setData({
      disabled: true
    });

    // 提交到后端
    values.address_id = _this.data.detail.address_id;
    App._post_form('enroll/add', values, function(result) {
      App.showSuccess(result.msg, function() {
        wx.navigateBack();
      });
      console.log(result);
    }, false, function() {
      // 解除禁用
      _this.setData({
        disabled: false
      });
    });
  },

  /**
   * 表单验证
   */
  validation: function(values) {
    if (values.name === '') {
      this.data.error = '真实姓名不能为空';
      return false;
    }
    if (values.sex == 0) {
      this.data.error = '请选择性别';
      return false;
    }

    //是否选择年龄 1=是，0=否
    if (values.is_age_group == 1){
      if (values.age_group == 0) {
        this.data.error = '年龄段不能为空';
        return false;
      }
    }else{
      if (values.age == 0) {
        this.data.error = '年龄不能为空';
        return false;
      }
    }

    if (values.mobile.length !== 11) {
      this.data.error = '手机号长度有误';
      return false;
    }
    let reg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1})|(19[0-9]{1}))+\d{8})$/;
    if (!reg.test(values.mobile)) {
      this.data.error = '手机号不符合要求';
      return false;
    }
    // if (!this.data.region) {
    //   this.data.error = '籍贯不能空';
    //   return false;
    // }
    // if (values.detail === '') {
    //   this.data.error = '现今所在不能为空';
    //   return false;
    // }

    if(this.data.images.length < 1){
      this.data.error = '请上传至少一张图片';
      return false;
    }

    return true;
  },

  /**
   * 修改地区
   */
  bindRegionChange: function(e) {
    this.setData({
      region: e.detail.value
    })
  },

  /**
   * 获取微信地址
   */
  chooseAddress: function() {
    let _this = this;
    wx.chooseAddress({
      success: function(res) {
        _this.setData({
          'detail.name': res.userName,
          'detail.phone': res.telNumber,
          'detail.detail': res.detailInfo,
          region: [res.provinceName, res.cityName, res.countyName],
        });
      }
    })
  },
  
  radioChange: function (e) {
    this.setData({
      check_sex: e.detail.value
    })
  },

  radioStatusChange: function (e) {
    this.setData({
      type: e.detail.value
    })
  },

  bindlongpressimg:function(e){
    let that = this;
    let key = e.target.dataset.id;
    let imagesArr = that.data.images;
    let showImagesArr = that.data.showImages;

    imagesArr.splice(key,1);
    showImagesArr.splice(key, 1);
    that.setData({
      images: imagesArr,
      showImages: showImagesArr
    })
    //console.log(that.data.images);
  },
  //查看图片
  previewImage: function (e) {
    let key = e.target.dataset.id;
    let imgSrc = this.data.showImages;
    wx.previewImage({
      current: imgSrc[key],
      urls: imgSrc
    })
  },
  //发起图片提交
  img_item: function (e) {
    var that = this;
    if (that.data.showImages.length > 3){
      App.showError('只可上传3张图片', function () {
      });
      return false;
    }

    wx.chooseImage({
      count: 3,
      sizeType: ['original'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        if ((that.data.showImages.length + res.tempFilePaths.length) > 3) {
          App.showError('只可上传3张图片', function () {
          });
          return false;
        }

        that.setData({
          'tempFilePaths': res.tempFilePaths
        })
        //console.log(that.data.tempFilePaths);
        that.btn_up();
      }
    })
  },
  //提交图片
  btn_up: function (e) {
    var that = this;
    wx.showLoading({
      title: '图片上传中，请耐心等待',
    })
    let token = wx.getStorageSync('token');
    wx.uploadFile({
      url: App.api_root + 'address/addImage', // 仅为示例，非真实的接口地址
      filePath: that.data.tempFilePaths[i],
      name: 'file',
      formData: {
        wxapp_id: App.siteInfo.uniacid,
        token: token
      },
      success(res) {
        //console.log(res);
        let arr = JSON.parse(res.data);
        if(arr.code == 1){
          let arr2 = JSON.parse(arr.data);
          var showImagesArr = that.data.showImages;
          showImagesArr.push(App.root + arr2.url);
          var imagesArr = that.data.images; 
          imagesArr.push(arr2.url);
          that.setData({
            'showImages': showImagesArr,
            'images': imagesArr
          })
          i++;
          if (i < that.data.tempFilePaths.length) {
            that.btn_up();
          }
        }else{
          App.showError(arr.msg);
        }
        wx.hideLoading();
      }
    })
  },

  //是否选择年龄段
  radioChangeSex:function(e){
    let index = e.detail.value;
    this.setData({
      is_age_group: index
    })
  },


  //修改年龄段
  bindPickerChange: function (e) {
    let index = e.detail.value;
    this.setData({
      sex_index: index
    })
  },

})